package com.epalmpay.service.apiXdlPay.impl;

import com.epalmpay.entity.Group;
import com.epalmpay.entity.Member;
import com.epalmpay.entity.TradeOffline;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.mapper.GroupMapper;
import com.epalmpay.mapper.MemberMapper;
import com.epalmpay.mapper.TradeOfflineMapper;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.IXDLPayAPI;
import com.epalmpay.payplat.PayBalanceQuery;
import com.epalmpay.payplat.XDLScanPay;
import com.epalmpay.payplat.result.PayBalanceResult;
import com.epalmpay.payplat.result.XDLScanPayResult;
import com.epalmpay.service.apiXdlPay.IApiXdlService;
import com.epalmpay.status.Rescode;
import com.epalmpay.util.Response;
import com.epalmpay.util.StringUtil;
import com.epalmpay.util.payplat.UtilFun;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/4/20.
 */
@Service("apiXdlService")
public class ApiXdlServiceImpl implements IApiXdlService{
    @Resource
    private MemberMapper memberMapper;

    @Resource
    private GroupMapper groupMapper;

    @Resource
    private TradeOfflineMapper tradeOfflineMapper;

    @Override
    public Response goPay(String memberId,String groupId,String mchntid, String termid, String amount, String total_amount,
                          String auth_code, String paychannel, String goodsdesc, String tradeno) throws ApplicationException {
        Map<String,Object> map = new HashMap<String,Object>();

        Member member = null;
        if(memberId!=null){
            member = memberMapper.selectByPrimaryKey(Long.parseLong(memberId));
        }
        Group group = groupMapper.selectByPrimaryKey(Long.parseLong(groupId));

        tradeno= UtilFun.createOrderNum("XDL");
        if(StringUtil.isEmpty(goodsdesc)){
            goodsdesc="";
        }

        XDLScanPay xdlScanPay=XDLScanPay.initialize(mchntid, termid, amount, total_amount,
                auth_code, paychannel,goodsdesc,tradeno,null);
        XDLScanPayResult xdlScanPayResult = IXDLPayAPI.scanPayfinsh(xdlScanPay);
        if (!xdlScanPayResult.getResult_code().equals("000000")) {
            throw new ApplicationException(Rescode.FAIL,xdlScanPayResult.getResult_msg());
        }
        //交易成功
        if(xdlScanPayResult.getResult().equals("S")){
            TradeOffline tradeOffline =new TradeOffline();
            tradeOffline.setOrderId(xdlScanPayResult.getSelOrderNo());//商博士订单号
            if(member !=null){
                tradeOffline.setPayerId(member.getId());
                tradeOffline.setPayerName(member.getName());
            }else{
                tradeOffline.setPayerId(null);
                tradeOffline.setPayerName(null);
            }
            tradeOffline.setGmtCreate(new Date());
            tradeOffline.setGmtModified(new Date());
            tradeOffline.setGroupId(Long.parseLong(groupId));
            tradeOffline.setReceiverId(groupId);
            tradeOffline.setReceiverName(group.getMerchantName());
            tradeOffline.setReceiverType((byte) CommonEnum.UserType.BusinessManager.getType());
            tradeOffline.setRealAmount(Integer.parseInt(amount));
            tradeOffline.setOrderAmount(Integer.parseInt(total_amount));

            tradeOffline.setTransNo(xdlScanPayResult.getOrderNo());//交易订单号可用于退款
            tradeOffline.setTransOrderNo(xdlScanPayResult.getLogNo());//支付公司系统流水号
            tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());
            if(paychannel.equals("ALIPAY")){
                tradeOffline.setPayType((byte)BizEnum.PaymentType.AliPay.getType());
            }else{
                tradeOffline.setPayType((byte)BizEnum.PaymentType.WebChat.getType());
            }
            tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
            tradeOffline.setMemo(goodsdesc);
            tradeOffline.setMerchantNo(mchntid);
            tradeOffline.setTerminalNo(termid);

            tradeOfflineMapper.insertSelective(tradeOffline);
        }
        if(xdlScanPayResult.getResult().equals("A")){
            TradeOffline tradeOffline =new TradeOffline();
            tradeOffline.setOrderId(xdlScanPayResult.getSelOrderNo());//商博士订单号
            if(member !=null){
                tradeOffline.setPayerId(member.getId());
                tradeOffline.setPayerName(member.getName());
            }else{
                tradeOffline.setPayerId(null);
                tradeOffline.setPayerName(null);
            }
            tradeOffline.setGmtCreate(new Date());
            tradeOffline.setGmtModified(new Date());
            tradeOffline.setGroupId(Long.parseLong(groupId));
            tradeOffline.setReceiverId(groupId);
            tradeOffline.setReceiverName(group.getMerchantName());
            tradeOffline.setReceiverType((byte) CommonEnum.UserType.BusinessManager.getType());
            tradeOffline.setRealAmount(Integer.parseInt(amount));
            tradeOffline.setOrderAmount(Integer.parseInt(total_amount));

            tradeOffline.setTransNo(xdlScanPayResult.getOrderNo());//交易订单号可用于退款
            tradeOffline.setTransOrderNo(xdlScanPayResult.getLogNo());//支付公司系统流水号
            tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());
            if(paychannel.equals("ALIPAY")){
                tradeOffline.setPayType((byte)BizEnum.PaymentType.AliPay.getType());
            }else{
                tradeOffline.setPayType((byte)BizEnum.PaymentType.WebChat.getType());
            }
            tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.WaitingForPay.getType());
            tradeOffline.setMemo(goodsdesc);
            tradeOffline.setMerchantNo(mchntid);
            tradeOffline.setTerminalNo(termid);

            tradeOfflineMapper.insertSelective(tradeOffline);
        }
        return Response.getSuccess(xdlScanPayResult);
    }

    /**
     *
     * @param mchntid
     * @param termid
     * @param tradeno //本地订单号
     * @return
     * @throws ApplicationException
     */
    @Override
    public Response goQueryOrderNo(String mchntid, String termid, String tradeno) throws ApplicationException {

        XDLScanPayResult xdlScanPayResult;

        XDLScanPay xdlScanPay=XDLScanPay.initialize(mchntid, termid, null, null,
                null, null,null,tradeno,null);

         xdlScanPayResult = IXDLPayAPI.scanbarquery(xdlScanPay);
        if (!xdlScanPayResult.getResult_code().equals("000000")) {
            throw new ApplicationException(Rescode.FAIL,xdlScanPayResult.getResult_msg());
        }

        if(xdlScanPayResult.getResult().equals("S")){
            //根据订单号查询 交易记录
            TradeOffline tradeOffline = tradeOfflineMapper.selectQueryOrderInfo(mchntid,termid,tradeno);
            if(tradeOffline.getTransactionStatus()==BizEnum.TransactionStatus.Success.getType()){
                return Response.getSuccess(xdlScanPayResult);
            }
            if(tradeOffline.getTransactionStatus()==BizEnum.TransactionStatus.WaitingForPay.getType()){
                tradeOffline.setGmtModified(new Date());
                tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                //在去查询新大陆订单记录
                String transNo = tradeOffline.getTransOrderNo();
                XDLScanPay xdlScanPay2=XDLScanPay.initialize(mchntid, termid, null, null,
                        null, null,null,transNo,null);

                xdlScanPayResult = IXDLPayAPI.scanbarquery(xdlScanPay);
                if (!xdlScanPayResult.getResult_code().equals("000000")) {
                    throw new ApplicationException(Rescode.FAIL,xdlScanPayResult.getResult_msg());
                }
                if(xdlScanPayResult.getResult().equals("S")){
                    tradeOffline.setTransNo(xdlScanPayResult.getOrderNo());
                    tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
                }
                return Response.getSuccess(xdlScanPayResult);

            }

        }
        return Response.getSuccess(xdlScanPayResult);
    }

    @Override
    public Response scanbarrefund(String mchntid, String termid, String tradeno, String txnAmt) throws ApplicationException {

        XDLScanPay xdlScanPay=XDLScanPay.initialize(mchntid, termid, null, null,
                null, null,null,tradeno,txnAmt);
        XDLScanPayResult xdlScanPayResult = IXDLPayAPI.scanbarrefund(xdlScanPay);
        if (!xdlScanPayResult.getResult_code().equals("000000")) {
            throw new ApplicationException(Rescode.FAIL,xdlScanPayResult.getResult_msg());
        }

        if(xdlScanPayResult.getResult().equals("S")){

            TradeOffline tradeOffline = tradeOfflineMapper.selectOrderInfo(mchntid,termid,tradeno);
            if(tradeOffline.getTransactionStatus()==BizEnum.TransactionStatus.ISRefund.getType()){

                return Response.getError("这笔订单已退款");
            }
            if(tradeOffline.getTransactionStatus()==BizEnum.TransactionStatus.Success.getType()){

                tradeOffline.setGmtModified(new Date());
                tradeOffline.setRealAmount(-1*tradeOffline.getRealAmount());
                tradeOffline.setOrderAmount(-1*tradeOffline.getOrderAmount());
                tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Refund.getType());
                tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.ISRefund.getType());

                tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

                //生成一条新的
                TradeOffline tradeOffline1 = new TradeOffline();

                if(tradeOffline.getPayerId() !=null){
                    tradeOffline1.setPayerId(tradeOffline.getPayerId());
                    tradeOffline1.setPayerName(tradeOffline.getPayerName());
                }else{
                    tradeOffline1.setPayerId(null);
                    tradeOffline1.setPayerName(null);
                }
                tradeOffline1.setGmtCreate(new Date());
                tradeOffline1.setGmtModified(new Date());
                tradeOffline1.setGroupId(tradeOffline.getGroupId());
                tradeOffline1.setReceiverId(tradeOffline.getGroupId().toString());
                tradeOffline1.setReceiverName(tradeOffline.getReceiverName());
                tradeOffline1.setReceiverType((byte) CommonEnum.UserType.BusinessManager.getType());
                tradeOffline1.setRealAmount(-1*tradeOffline.getRealAmount());
                tradeOffline1.setOrderAmount(-1*tradeOffline.getOrderAmount());

                tradeOffline1.setTransactionType((byte)BizEnum.TransactionType.Consumption.getType());
                tradeOffline1.setPayType(tradeOffline.getPayerType());
                tradeOffline1.setTransactionStatus((byte)BizEnum.TransactionStatus.Refund.getType());
                tradeOffline1.setMerchantNo(mchntid);
                tradeOffline1.setTerminalNo(termid);
                tradeOffline1.setOrderId(UtilFun.createOrderNum("XDL"));
                tradeOffline1.setTransactionType((byte)BizEnum.TransactionType.Refund.getType());
                tradeOfflineMapper.insertSelective(tradeOffline1);

                return Response.getSuccess(xdlScanPayResult);
            }

        }
        return Response.getSuccess(xdlScanPayResult);
    }
}
